package com.helloscala.helper

import org.joda.time._
import com.helloscala.common.HelloConfig
import net.liftweb.http.LiftRules
import java.io.{FileInputStream, InputStream, InputStreamReader}

object HelloHelpers {
  // TODO 从MUser中获取
  def avatarUri(id: String): String =
    s"/upload/user/${id}/avatar-32.png"

  def timeDescription(at: DateTime): String = {
    val now = DateTime.now()

    yearsBetween(at, now).map(i => s"于${i}年前发布") orElse
      monthsBetween(at, now).map(i => s"于${i}个月前发布") orElse
      weeksBetween(at, now).map(i => s"于${i}周前发布") orElse
      daysBetween(at, now).map(i => s"于${i}天前发布") orElse
      hoursBetween(at, now).map(i => s"于${i}小时前发布") orElse
      minutesBetween(at, now).map(i => s"于${i}分钟前发布") getOrElse
      "刚发布"
  }

  def yearsBetween(at: DateTime, now: DateTime) =
    _between(Years.yearsBetween(at, now).getYears)

  def monthsBetween(at: DateTime, now: DateTime) =
    _between(Months.monthsBetween(at, now).getMonths)

  def weeksBetween(at: DateTime, now: DateTime) =
    _between(Weeks.weeksBetween(at, now).getWeeks)

  def daysBetween(at: DateTime, now: DateTime) =
    _between(Days.daysBetween(at, now).getDays)

  def hoursBetween(at: DateTime, now: DateTime) =
    _between(Hours.hoursBetween(at, now).getHours)

  def minutesBetween(at: DateTime, now: DateTime) =
    _between(Minutes.minutesBetween(at, now).getMinutes)

  @inline
  private def _between(days: Int): Option[Int] =
    if (days > 0) Some(days) else None

  import org.json4s._
  import org.json4s.native._
  import yangbajing.util.Imports.Y.json4sDefaultAndJodaTimeFormats

  lazy val config: HelloConfig =
    LiftRules.doWithResource("/WEB-INF/hello-config.json")(in => config(in)) openOr
      config(new FileInputStream("/data/workspace/helloscala/app/helloscala/src/main/webapp/WEB-INF/hello-config.json"))

  def config(in: InputStream, charset: String = "UTF-8"): HelloConfig =
    JsonParser.parse(new InputStreamReader(in, charset)).extract[HelloConfig]

}
